#include "App.hh"

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

#include <iostream>
#include <stdexcept>

#include "math.hh"

using namespace sirtet;
using namespace std;

App::App(std::unique_ptr<Node> scene, AppConfig &&config)
{
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        throw std::runtime_error("SDL init failed");
    }

    if (IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG)
    {
        throw std::runtime_error("SDL_image init failed");
    }

    window = SDL_CreateWindow(config.app_name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                              config.window_width, config.window_height, 0);

    auto engine = Engine::instance();
    engine->init(window);
    engine->get_root().add_child(std::move(scene));
}

App::~App()
{
    Engine::deinit();
    SDL_DestroyWindow(window);
}

void App::run()
{
    bool running = true;
    SDL_Event e;
    do
    {
        while (SDL_PollEvent(&e))
        {
            if (e.type == SDL_QUIT)
            {
                running = false;
            }
        }

        auto engine = Engine::instance();
        engine->update();
        engine->after_update();

        SDL_Delay(100);
    } while (running);
}
